package com.itheima.reggie.intercepter;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.utils.EmpThreadLocal;
import com.itheima.reggie.utils.UserThreadLocal;
import com.itheima.reggie.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandle;

/**
 * 校验用户是否完成登录
 * 登录拦截
 */

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    //在请求到达Controller前去执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //handler对象是请求要去找的目标资源
        //如果当前请求的是静态资源就直接放行
        if (!(handler instanceof HandlerMethod)) return true;

        //获取请求路径
        log.info("请求路径：{}", request.getRequestURL());
        log.info("请求路径：{}", request.getRequestURI());
        if (request.getRequestURI().contains("employee/login")) return true;
        if (request.getRequestURI().contains("user/sendMsg")) return true;
        if (request.getRequestURI().contains("user/login")) return true;

        //先判断请求的资源是不是登录，如果是，放行
        if (ObjectUtil.isNotNull(request.getSession().getAttribute("employee"))) {
            //把登录信息绑定到当前线程
            EmpThreadLocal.set((Employee) request.getSession().getAttribute("employee"));
            return true;
        }
        if (ObjectUtil.isNotNull(request.getSession().getAttribute("user"))) {
            //把登录信息绑定到当前线程
            UserThreadLocal.set((User) request.getSession().getAttribute("user"));
            return true;
        }

        //如果没有登录，返回401
        //设置响应状态码
        response.setStatus(401);
        //设置响应头信息
        response.setContentType("application/json;charset=utf-8");
        //设置响应内容
        response.getWriter().println(JSONUtil.toJsonStr(R.error("用户未登录")));
        return false;
    }

/*
*
     * 在请求到达Controller之后返回浏览器之前执行

*/

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        EmpThreadLocal.remove();
    }
}
